<template>
  <div class="success-page">
    <div class="container">
      <!-- 返回按钮 -->
      <button class="back-btn" @click="convertNew">
        ← 返回
      </button>

      <!-- 标题区域 -->
      <div class="page-header">
        <h1 class="page-title">GIF预览</h1>
      </div>

      <!-- 主内容卡片 -->
      <div class="content-card">
        <!-- GIF预览区域 - 优化性能 -->
        <div class="gif-preview-section">
          <!-- 加载动画 -->
          <div v-if="gifLoading && !gifReady" class="gif-loading">
            <div class="gif-loading-spinner"></div>
            <div class="gif-loading-text">GIF正在加载，请耐心等待…</div>
            <div v-if="gifData.gifFileSize > 5 * 1024 * 1024" class="gif-loading-hint">
              大文件动图加载会比较慢，建议等待页面完全加载后再下载。
            </div>
          </div>
          <!-- GIF图片 -->
          <div v-else-if="gifReady && gifData.gifUrl" class="gif-container">
            <img 
              :src="gifDataWithTimestamp" 
              alt="GIF预览" 
              class="gif-image"
              :class="{ 'gif-paused': isGifPaused }"
              loading="eager"
              decoding="async"
              @load="handleGifLoad"
              @error="handleImageError" 
            />
          </div>
        </div>

        <!-- 下载按钮 -->
        <button class="download-btn" @click="downloadGif">
          下载 GIF
        </button>

        <!-- 文件信息列表 -->
        <div class="info-list">
          <div class="info-row">
            <span class="info-label">分辨率:</span>
            <span class="info-value">{{ gifData.gifWidth }} × {{ gifData.gifHeight }}px</span>
          </div>
          <div class="info-row">
            <span class="info-label">文件大小:</span>
            <span class="info-value">{{ formatFileSize(gifData.gifFileSize) }}</span>
          </div>
        </div>
      </div>

      <!-- 成功提示 -->
      <div class="success-message">
        <span class="success-icon">✓</span>
        <div class="success-text">
          <strong>GIF 生成成功！</strong>
          <p>您的GIF已经准备就绪，可以预览、下载或分享。页面刷新后仍可正常访问。</p>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { toastSuccess, toastError } from '@/utils/toast'

const router = useRouter()
const gifData = ref({
  id: null,
  gifUrl: '',
  gifFilename: '',
  gifFileSize: 0,
  gifWidth: 0,
  gifHeight: 0
})
const gifLoading = ref(true)
const gifReady = ref(false)
const isGifPaused = ref(false) 

// 添加时间戳参数防止浏览器缓存
const gifDataWithTimestamp = computed(() => {
  if (!gifData.value.gifUrl) return ''
  const separator = gifData.value.gifUrl.includes('?') ? '&' : '?'
  return `${gifData.value.gifUrl}${separator}t=${Date.now()}`
})

const MAX_RETRIES = 6;
const RETRY_INTERVAL = 1500; // ms
let retryCount = 0;

// 增强后的图片加载错误处理，支持多次重试和强 loading 状态
const handleImageError = async (event) => {
  console.error('GIF加载失败:', gifData.value.gifUrl)
  console.error('完整URL:', event.target.src)

  // 仅重试指定次数
  if (retryCount < MAX_RETRIES && gifData.value.id) {
    retryCount += 1;
    gifLoading.value = true;
    gifReady.value = false;
    setTimeout(async () => {
      // 尝试重新拉取记录，是否切换到了COS代理url
      try {
        const response = await fetch(`/api/conversion/videoToGif/${gifData.value.id}`)
        const result = await response.json()
        if (result.code === 200 && result.data && result.data.gifUrl && result.data.gifUrl !== gifData.value.gifUrl) {
          gifData.value.gifUrl = result.data.gifUrl
          if (result.data.gifWidth) gifData.value.gifWidth = result.data.gifWidth
          if (result.data.gifHeight) gifData.value.gifHeight = result.data.gifHeight
          if (result.data.gifFileSize) gifData.value.gifFileSize = result.data.gifFileSize
          gifLoading.value = true;
          gifReady.value = false;
          await preloadGif(gifData.value.gifUrl, gifData.value.gifFileSize)
        } else {
          // 未切换，继续重试
          handleImageError(event)
        }
      } catch (e) {
        // 拉取失败，也继续重试
        handleImageError(event)
      }
    }, RETRY_INTERVAL)
    return
  }
  // 超过最大重试，隐藏loading，允许显示错误占位
  gifLoading.value = false;
  gifReady.value = true;
}

// GIF加载完成处理 - 优化性能
const handleGifLoad = (event) => {
  const img = event.target
  // 使用will-change提示浏览器优化
  img.style.willChange = 'auto'
  // 使用GPU加速
  img.style.transform = 'translateZ(0)'
  img.style.webkitTransform = 'translateZ(0)'
  
  // 🔑 对于大文件（>10MB），自动暂停以节省资源
  if (gifData.value.gifFileSize > 10 * 1024 * 1024) {
    isGifPaused.value = true
  }
}

// 🔑 切换GIF播放/暂停
// 注意：由于GIF是自包含的动画格式，无法真正暂停
// 这里通过重新加载GIF来实现"暂停"效果（显示第一帧）
const toggleGifPlay = () => {
  isGifPaused.value = !isGifPaused.value
  const img = document.querySelector('.gif-image')
  if (img) {
    if (isGifPaused.value) {
      // "暂停"：通过重新加载GIF来重置到第一帧
      // 这不是真正的暂停，但可以重置动画到开始
      const currentSrc = img.src
      img.src = ''
      // 使用setTimeout确保浏览器重置
      setTimeout(() => {
        img.src = currentSrc
      }, 10)
    } else {
      // "播放"：重新加载GIF以继续播放
      const currentSrc = img.src
      img.src = ''
      setTimeout(() => {
        img.src = currentSrc
      }, 10)
    }
  }
}

onMounted(async () => {
  // 从sessionStorage获取转换结果数据
  const resultData = sessionStorage.getItem('conversionResult')
  if (resultData) {
    const data = JSON.parse(resultData)
    gifData.value = data
    console.log('转换结果数据:', data)
    console.log('GIF URL:', data.gifUrl)
    console.log('GIF尺寸:', data.gifWidth, 'x', data.gifHeight)
    
    // 🔑 如果尺寸为0或缺失，且有ID，尝试从后端重新获取
    if ((!data.gifWidth || !data.gifHeight || data.gifWidth === 0 || data.gifHeight === 0) && data.id) {
      console.log('检测到尺寸信息缺失，尝试从后端重新获取...')
      try {
        const response = await fetch(`/api/conversion/videoToGif/${data.id}`)
        const result = await response.json()
        if (result.code === 200 && result.data) {
          // 更新尺寸信息
          if (result.data.gifWidth) {
            gifData.value.gifWidth = result.data.gifWidth
          }
          if (result.data.gifHeight) {
            gifData.value.gifHeight = result.data.gifHeight
          }
          // 更新其他可能缺失的字段
          if (result.data.gifFileSize) {
            gifData.value.gifFileSize = result.data.gifFileSize
          }
          if (result.data.gifUrl && !data.gifUrl) {
            gifData.value.gifUrl = result.data.gifUrl
          }
          console.log('从后端获取到尺寸信息:', gifData.value.gifWidth, 'x', gifData.value.gifHeight)
        }
      } catch (error) {
        console.error('从后端获取尺寸信息失败:', error)
      }
    }
    
    // 🔑 预加载GIF，等待完全加载后再显示
    if (gifData.value.gifUrl) {
      await preloadGif(gifData.value.gifUrl, gifData.value.gifFileSize)
    } else {
      gifLoading.value = false
      gifReady.value = true
    }
  } else {
    // 如果没有数据，跳转回首页
    router.push('/')
  }
})

// 🔑 预加载GIF（等待完全加载）
const preloadGif = (url, fileSize) => {
  return new Promise((resolve) => {
    gifLoading.value = true
    gifReady.value = false
    
    const img = new Image()
    
    // 设置超时（30秒）
    const timeout = setTimeout(() => {
      gifLoading.value = false
      gifReady.value = true
      console.warn('GIF加载超时，直接显示')
      resolve()
    }, 30000)
    
    // 计算GIF额外等待时间（根据文件大小）
    const getGifWaitTime = () => {
      if (!fileSize) return 800
      
      // 获取文件大小（MB）
      const fileSizeMB = fileSize / (1024 * 1024)
      
      // 根据文件大小动态调整等待时间
      // 小于5MB: 500ms
      // 5-10MB: 800ms
      // 10-20MB: 1200ms
      // 大于20MB: 2000ms
      if (fileSizeMB < 5) return 500
      if (fileSizeMB < 10) return 800
      if (fileSizeMB < 20) return 1200
      return 2000
    }
    
    img.onload = () => {
      clearTimeout(timeout)
      
      // 对于GIF，额外等待一段时间确保动画帧缓存完成
      const waitTime = getGifWaitTime()
      setTimeout(() => {
        gifLoading.value = false
        gifReady.value = true
        resolve()
      }, waitTime)
    }
    
    img.onerror = () => {
      clearTimeout(timeout)
      console.error('GIF预加载失败:', url)
      
      // 🔑 如果URL是本地文件URL且加载失败，尝试重新获取转换详情
      if (url && url.includes('/api/files/local') && gifData.value.id) {
        console.log('检测到本地文件URL预加载失败，尝试重新获取转换详情...')
        // 异步重新获取
        fetch(`/api/conversion/videoToGif/${gifData.value.id}`)
          .then(response => response.json())
          .then(result => {
            if (result.code === 200 && result.data && result.data.gifUrl) {
              const newUrl = result.data.gifUrl
              if (newUrl !== url && !newUrl.includes('/api/files/local')) {
                console.log('获取到新的GIF URL，更新并重新加载:', newUrl)
                // 🔑 更新所有字段，包括尺寸信息
                gifData.value.gifUrl = newUrl
                if (result.data.gifWidth) {
                  gifData.value.gifWidth = result.data.gifWidth
                }
                if (result.data.gifHeight) {
                  gifData.value.gifHeight = result.data.gifHeight
                }
                if (result.data.gifFileSize) {
                  gifData.value.gifFileSize = result.data.gifFileSize
                }
                // 重新预加载新URL（这会更新gifLoading和gifReady状态）
                preloadGif(newUrl, gifData.value.gifFileSize)
                resolve() // 当前Promise resolve，让新的preloadGif处理后续流程
                return
              }
            }
            // 如果无法获取新URL，直接显示
            gifLoading.value = false
            gifReady.value = true
            resolve()
          })
          .catch(error => {
            console.error('重新获取转换详情失败:', error)
            // 获取失败，直接显示
            gifLoading.value = false
            gifReady.value = true
            resolve()
          })
        return // 等待异步操作完成后再resolve
      }
      
      // 如果无法重新获取或重新获取失败，直接显示（让浏览器尝试加载，可能会显示错误）
      gifLoading.value = false
      gifReady.value = true
      resolve()
    }
    
    // 开始加载
    img.src = url
  })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

// 转换新视频
const convertNew = () => {
  // 清除sessionStorage中的数据
  sessionStorage.removeItem('conversionResult')
  // 跳转回首页
  router.push('/')
}

// 直接下载（不跳转页面）
const downloadGif = async () => {
  if (!gifData.value.gifUrl) {
    toastError('下载地址不存在')
    return
  }

  const downloadUrl = gifData.value.gifUrl
  const filename = gifData.value.gifFilename || 'output.gif'
  try {
    // 优先尝试fetch转blob，保证即使是代理或COS直链都可以
    const urlWithParam = downloadUrl.includes('?') ? `${downloadUrl}&download=true` : `${downloadUrl}?download=true`
    const res = await fetch(urlWithParam, {mode: 'cors'})
    if (!res.ok) throw new Error('下载失败：' + res.statusText)
    const blob = await res.blob()
    const blobUrl = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = blobUrl
    a.download = filename
    document.body.appendChild(a)
    a.click()
    setTimeout(() => { URL.revokeObjectURL(blobUrl); a.remove() }, 100)
    toastSuccess('下载成功')
  } catch (error) {
    // 如果fetch失败（如CORS等），降级用a标签直接下载
    try {
      const a = document.createElement('a')
      a.href = downloadUrl
      a.download = filename
      document.body.appendChild(a)
      a.click()
      a.remove()
      toastSuccess('下载已尝试发起')
    } catch (e) {
      console.error('下载降级失败:', e)
      toastError('下载失败: ' + (error.message || '网络错误，稍后重试'))
    }
  }
}
</script>

<style scoped>
.success-page {
  min-height: 100vh;
  width: 100vw;
  background: #f5f7fa;
  padding: 40px 20px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow-x: hidden;
}

.container {
  max-width: 600px;
  width: 100%;
  margin: 0 auto;
}

/* 返回按钮 */
.back-btn {
  background: white;
  border: 1px solid #e5e7eb;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 0.95rem;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 20px;
  font-weight: 500;
}

.back-btn:hover {
  background: #f9fafb;
  border-color: #d1d5db;
}

/* 页面标题 */
.page-header {
  background: #e0e7ff;
  padding: 16px 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.header-icon {
  font-size: 1.5rem;
}


.page-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

/* 主内容卡片 */
.content-card {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* GIF预览区域 */
.gif-preview-section {
  background: #f9fafb;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  margin-bottom: 24px;
  position: relative;
  /* 🔑 GIF容器性能优化 */
  will-change: scroll-position;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  /* 使用GPU加速 */
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  /* 优化滚动 */
  -webkit-overflow-scrolling: touch;
}

/* GIF加载等待页面 */
.gif-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  z-index: 5;
  gap: 16px;
}

.gif-loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f4f6;
  border-top-color: #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.gif-loading-text {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.gif-loading-hint {
  font-size: 13px;
  color: #6b7280;
  margin: 0;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.gif-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.gif-image {
  max-width: 100%;
  max-height: 500px;
  width: auto;
  height: auto;
  display: block;
  object-fit: contain;
  border-radius: 8px;
  /* 🔑 GIF性能优化 - 硬件加速和渲染优化 */
  will-change: contents;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  /* 使用GPU加速 */
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  /* 优化渲染 */
  image-rendering: auto;
  -webkit-font-smoothing: antialiased;
  /* 减少重绘 */
  contain: layout style paint;
  /* 优化动画性能 */
  -webkit-perspective: 1000;
  perspective: 1000;
  /* 🔑 性能优化：减少重绘频率 */
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  /* 🔑 暂停状态：降低渲染优先级 */
  transition: opacity 0.2s;
}

.gif-image.gif-paused {
  /* 暂停时降低不透明度，提示用户 */
  opacity: 0.9;
  filter: brightness(0.95);
}

/* 🔑 播放控制按钮 */
.gif-play-control {
  position: absolute;
  top: 16px;
  right: 16px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.gif-play-control:hover {
  background: rgba(0, 0, 0, 0.9);
  transform: scale(1.1);
}

/* 🔑 性能提示 */
.gif-performance-hint {
  margin-top: 16px;
  padding: 12px 16px;
  background: #fef3c7;
  border: 1px solid #fcd34d;
  border-radius: 8px;
  font-size: 0.85rem;
  color: #92400e;
  text-align: center;
  max-width: 100%;
}

.gif-performance-hint p {
  margin: 4px 0;
  line-height: 1.4;
}

.gif-performance-hint p:first-child {
  font-weight: 600;
}

/* 下载按钮 */
.download-btn {
  width: 100%;
  background: #10b981;
  color: white;
  border: none;
  padding: 16px;
  border-radius: 10px;
  font-size: 1.05rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 24px;
}

.download-btn:hover {
  background: #059669;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

/* 信息列表 */
.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
  gap: 8px;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 0.95rem;
  color: #6b7280;
  font-weight: 500;
  min-width: 100px;
}

.info-value {
  font-size: 0.95rem;
  color: #111827;
  font-weight: 500;
}

/* 成功提示 */
.success-message {
  background: #d1fae5;
  border: 1px solid #a7f3d0;
  border-radius: 12px;
  padding: 20px 24px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.success-icon {
  width: 28px;
  height: 28px;
  background: #10b981;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: bold;
  flex-shrink: 0;
}

.success-text {
  flex: 1;
}

.success-text strong {
  display: block;
  font-size: 1.05rem;
  color: #065f46;
  margin-bottom: 6px;
}

.success-text p {
  font-size: 0.9rem;
  color: #047857;
  margin: 0;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .success-page {
    padding: 16px;
  }

  .content-card {
    padding: 24px;
  }

  .gif-preview-section {
    min-height: 300px;
    padding: 16px;
  }

  .page-title {
    font-size: 1.1rem;
  }

  .download-btn {
    padding: 14px;
    font-size: 1rem;
  }

  .success-message {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .page-header {
    padding: 12px 16px;
  }

  .content-card {
    padding: 20px;
  }

  .info-label {
    font-size: 0.85rem;
    min-width: 80px;
  }

  .info-value {
    font-size: 0.85rem;
  }
}
</style>


